﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Kotonoha.Server.Db.Dao;
using Kotonoha.Server.Objects.Model;
using Kotonoha.Objects.Selectors;
using Kotonoha.Server.Core.Utils;
using Kotonoha.Server.Model;
using Kotonoha.Server.Settings;
using Kotonoha.Server.Synch;
using NHibernate;

namespace Kotonoha.Server.UI.Synch {
    /// <summary>
    /// Interaction logic for SynchForm.xaml
    /// </summary>
    public partial class SynchForm : Window {
        public SynchForm() {
            InitializeComponent();

            Setting s = SettingsManager.Acquire("synch");
            object o = s["items-num"];
            if (o == null) {
                s["items-num"] = 50;
            }
        }

        private void SynchBtn_Click(object sender, RoutedEventArgs e) {
            Synchronizer synch = new Synchronizer();
            synch.ContainerFnc = makeContainer;
            Status.Text = synch.synchronize() ? "OK" : "Failed";
        }

        private static Container makeContainer() {
            Container c = new Container();
            Container old = new Container();
            ISession session = HibernateUtil.Model.Session;
            old.Words = session.CreateCriteria(typeof (Word)).List<Word>().ToList();
            Setting s = SettingsManager.Acquire("synch");
            HashSet<string> chs = new HashSet<string>();

            int count = (int)(s["items-num"] ?? 50);

            while (count > 0) {
                SimpleWordSelector sel = new SimpleWordSelector(old);
                Word selected = sel.Selected;
                if (!c.Words.Contains(selected)) {
                    c.Words.Add(selected);
                    --count;
                    chs.UnionWith(KanjiFactory.enumerateKanji(selected.Writing));
                }
            }
            c.Kanji = new ModelDao(session).findAllKanji(chs);
            return c;
        }
    }
}
